import time
import re

# 网络接口统计信息的文件路径
PROC_NET_DEV = '/proc/net/dev'

def parse_network_stats():
    """
    解析 /proc/net/dev 文件，返回一个字典，包含每个网络接口的接收和发送字节数。
    """
    stats = {}
    with open(PROC_NET_DEV, 'r') as f:
        lines = f.readlines()

    for line in lines[2:]:
        parts = re.split(r'\s+', line.strip())
        if len(parts) >= 17:
            iface = parts[0].strip(':')
            rx_bytes = int(parts[1])
            tx_bytes = int(parts[9])
            stats[iface] = {'rx_bytes': rx_bytes, 'tx_bytes': tx_bytes}

    return stats

def monitor_traffic(interval=5):
    """
    定期监控网络流量并输出流量变化。
    :param interval: 监控间隔时间（秒）
    """
    prev_stats = parse_network_stats()

    while True:
        time.sleep(interval)
        curr_stats = parse_network_stats()

        for iface, curr_data in curr_stats.items():
            if iface in prev_stats:
                prev_data = prev_stats[iface]
                rx_diff = curr_data['rx_bytes'] - prev_data['rx_bytes']
                tx_diff = curr_data['tx_bytes'] - prev_data['tx_bytes']

                print(f"Interface: {iface}")
                print(f"  Incoming bytes: {rx_diff} bytes")
                print(f"  Outgoing bytes: {tx_diff} bytes")
                print()

        # 更新上一轮的统计数据
        prev_stats = curr_stats

if __name__ == "__main__":
    monitor_traffic()
